package cn.itcast.intercepter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

@ControllerAdvice
public class CacheResponseBodyAdvice implements ResponseBodyAdvice {
    @Value("${health.cache.enable}")
    private Boolean enable;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return enable && methodParameter.hasMethodAnnotation(Cache.class);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        try {
            //ObjectMapper mapper = new ObjectMapper();
            String redisVaule = OBJECT_MAPPER.writeValueAsString(o);
            String redisKey = CacheIntercepter.createRedisKey(((ServletServerHttpRequest) serverHttpRequest).getServletRequest());
            Cache cache = methodParameter.getMethodAnnotation(Cache.class);
            //将数据添加到redis缓存中
            redisTemplate.opsForValue().set(redisKey, redisVaule, Long.valueOf(cache.time()), TimeUnit.SECONDS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return o;
    }
}
